package com.start.workflow.act;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.start.common.entity.StartBaseUser;
import com.start.workflow.vo.StartActNodeAction;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.task.Task;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class StartProcTaskInst extends StartProcTaskDef {
    @Schema(name = "节点实例id")
    private String taskInstId;
    @Schema(name = "节点实际处理人")
    private StartBaseUser handlerUser;
    @Schema(name = "节点处理状态")
    private Integer handlerState;

    @Schema(name = "节点表单数据")
    private JSONObject nodeFormData;

    @Schema(name = "审批时间")
    private LocalDateTime authDateTime;

    @Schema(name = "任务创建时间")
    private LocalDateTime createTime;
    @Schema(name = "耗时", description = "单位毫秒")
    private long durationInMillis;
    @Schema(name = "审批备注")
    private String authComment;

    public StartProcTaskInst() {

    }

    public StartProcTaskInst(Task task) {
        super(task);
    }

    public StartProcTaskInst(UserTask userTask) {
        super(userTask);
    }

    public StartProcTaskInst(HistoricActivityInstance activityInstance) {
        super(activityInstance);
        taskInstId = activityInstance.getTaskId();
        createTime = (DateUtil.toLocalDateTime(activityInstance.getStartTime()));
        authDateTime = (DateUtil.toLocalDateTime(activityInstance.getEndTime()));
        durationInMillis = activityInstance.getDurationInMillis();
    }


    public void initComment(List<StartActNodeAction> comments) {
        if (comments.isEmpty()) {
            return;
        }
        StartActNodeAction nodeAction = comments.get(0);
        if (comments.size() > 1) {
            comments = comments.stream().sorted(Comparator.comparing(StartActNodeAction::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
            nodeAction = comments.get(0);
        }
        handlerState = nodeAction.getHandlerStatus();
        authComment = nodeAction.getHandlerOpinion();
    }
}
